package com.heima.comment.service.impl;

import com.heima.comment.service.CommentHotService;
import com.heima.model.comment.pojos.ApComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


/**
 * @author admin
 */
@Service
@Slf4j
public class CommentHotServiceImpl implements CommentHotService {
    @Resource
    MongoTemplate mongoTemplate;

    /**
     * @param entryId
     * @param apComment
     * @Description 当此方法在Spring对象中被调用时, 会使用taskExecutor所配置的线程池 异步的执行
     */
    @Async("taskExecutor")
    @Override
    public void hotCommentExecutor(Long entryId, ApComment apComment) {
        log.info("计算热评异步方法开始 ==> {}", apComment);
        //1. 按照文章ID(entryId)查询热点评论：flag = 1，则按照点赞降序
        Query queryHot = Query.query(Criteria.where("entryId").is(entryId).and("flag").is(1))
                .with(Sort.by(Sort.Direction.DESC, "likes"));
        List<ApComment> hotCommentList = mongoTemplate.find(queryHot, ApComment.class);
        //2. 如果没有热评或者热评的数量 < 5,修改当前评论为热评
        if (hotCommentList.isEmpty() || hotCommentList.size() < 5) {
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            return;
        }
        //3. 如果热评数量大于等于5
        //3.1 将热评集合中最后一条热评和当前评论做对比
        ApComment lastHotComment = hotCommentList.get(hotCommentList.size() - 1);
        //3.2 如果当前评论点赞数>最后一条热评点赞数
        if (apComment.getLikes() > lastHotComment.getLikes()) {
            //将当前评论修改为热评
            apComment.setFlag((short) 1);
            mongoTemplate.save(apComment);
            //将最后一条评论改为普通评论
            lastHotComment.setFlag((short) 0);
            mongoTemplate.save(lastHotComment);
        }
    }
}
